package com.hlw.hr_man.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.hlw.hr_man.daoImpl.EmployeeDaoImpl;
import com.hlw.hr_man.service.EmployeeSrevice;
import com.hlw.hr_man.serviceImpl.EmployeeServiceImpl;
/**
 * 导入员工信息表
 * @author Windy--Chow
 *
 */
public class UploadEmployeescontroller extends HttpServlet{
    
	  EmployeeSrevice employee = new EmployeeServiceImpl();
	@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	// TODO Auto-generated method stub
    	doPost(req, resp);
    }
      @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	// TODO Auto-generated method stub
    	  req.setCharacterEncoding("utf8");
  		  resp.setCharacterEncoding("utf8");
    	  PrintWriter pw = resp.getWriter();
    	  
    	//1.得到FileItem的集合
  		 DiskFileItemFactory factory = new DiskFileItemFactory();
  		 ServletFileUpload upload = new ServletFileUpload(factory);
  		 
  		//设置上传最大大小
 		upload.setSizeMax(1024 * 1024 * 5);
 		upload.setHeaderEncoding("utf-8");
  		 
  		 List<FileItem> items;
  		 try {
			items = upload.parseRequest(req);
			String filename = items.get(0).getName();  //获取文件名
			StringBuffer path = new StringBuffer("d:/abc/");  //目录地址
			File file = new File(path.toString());
			file.mkdirs();  //创建一个目录用来上传时用
			path.append(filename); // 文件地址
			File newfile = new File(path.toString());
			newfile.createNewFile(); //创建一个新文件
			InputStream in = items.get(0).getInputStream();  //把文件内容先读进  再写进新目录
			byte[] buffer = new byte[1024];
			int len = 0;
			OutputStream out = new FileOutputStream(path.toString());
			while((len = in.read(buffer)) != -1){
				out.write(buffer, 0, len);
			}
			out.close();
			in.close();
			if(employee.uploadEmployees(path.toString())){
				pw.write("1");
			}
			else{
				pw.write("0");
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
